package com.gmstu.springframework.mvc.servlet;

import com.gmstu.mvcservlet.annotation.GpController;
import com.gmstu.mvcservlet.annotation.GpRequestMapping;
import com.gmstu.mvcservlet.annotation.GpRequestParam;
import com.gmstu.springframework.context.GpApplicationContext;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author John.zhang
 * @version Id: GpDispatcherServlet, v 1.0 2020/8/22 21:25 ZhiYong Exp $
 */
@Slf4j
public class GpDispatcherServlet extends HttpServlet {

    private final String CONTEXT_CONFIG_LOCATION = "contextApplicationConfig";

    private GpApplicationContext context;

    private List<GpHandlerMapping> handlerMappings = new ArrayList<GpHandlerMapping>();

    private Map<GpHandlerMapping, GpHandlerAdapter> handlerAdapters = new HashMap<GpHandlerMapping, GpHandlerAdapter>();

    private List<GpViewResolver> viewResolvers = new ArrayList<GpViewResolver>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            this.doDispatch(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        GpHandlerMapping handler = getHandler(req);

        if (handler == null) {
            processDispatchResult(req, resp, new GpModelAndView("404"));
            return;
        }
        GpHandlerAdapter handlerAdapter = getHandlerAdapter(handler);
        GpModelAndView modelAndView = handlerAdapter.handle(req, resp, handler);

        processDispatchResult(req, resp, modelAndView);
    }

    private GpHandlerAdapter getHandlerAdapter(GpHandlerMapping handler) {
        if (this.handlerAdapters.isEmpty()) {
            return null;
        }
        GpHandlerAdapter handlerAdapter = this.handlerAdapters.get(handler);
        if (handlerAdapter.supports(handler)) {
            return handlerAdapter;
        }
        return null;
    }

    private void processDispatchResult(HttpServletRequest req, HttpServletResponse resp, GpModelAndView modelAndView) throws IOException {
        if (null == modelAndView) {
            return;
        }
        if (this.viewResolvers.isEmpty()) {
            return;
        }
        for (GpViewResolver viewResolver : this.viewResolvers) {
            GpView view = viewResolver.resolveViewName(modelAndView.getViewName(), null);
            view.render(modelAndView.getModel(), req, resp);
            return;
        }
    }

    private GpHandlerMapping getHandler(HttpServletRequest req) {
        if (this.handlerMappings.isEmpty()) {
            return null;
        }
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();

        url = url.replaceAll(contextPath, "").replaceAll("/+", "/");

        for (GpHandlerMapping handler : this.handlerMappings) {
            Matcher matcher = handler.getPattern().matcher(url);
            if (!matcher.matches()) {
                continue;
            }
            return handler;
        }
        return null;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        context = new GpApplicationContext(config.getInitParameter(CONTEXT_CONFIG_LOCATION));

        initStrategies(context);
    }

    private void initStrategies(GpApplicationContext context) {

        initHandlerMappings(context);

        initHandlerAdapters(context);

        initViewResolvers(context);
    }

    private void initViewResolvers(GpApplicationContext context) {
        String templateRoot = context.getConfig().getProperty("templateRoot");
        String templateRootPath = this.getClass().getClassLoader().getResource(templateRoot).getFile();

        File templateRootDir = new File(templateRootPath);
        String[] templates = templateRootDir.list();
        for (int i = 0; i < templates.length; i++) {
            this.viewResolvers.add(new GpViewResolver(templateRoot));
        }
    }

    private void initHandlerAdapters(GpApplicationContext context) {
        for (GpHandlerMapping handlerMapping : this.handlerMappings) {
            this.handlerAdapters.put(handlerMapping, new GpHandlerAdapter());
        }
    }

    private void initHandlerMappings(GpApplicationContext context) {

        String[] beanNames = context.getBeanDefinitionNames();

        for (String beanName : beanNames) {
            Object controller = context.getBean(beanName);
            Class<?> clazz = controller.getClass();

            if (!clazz.isAnnotationPresent(GpController.class)) {
                continue;
            }
            String baseUrl = "";
            if (clazz.isAnnotationPresent(GpRequestMapping.class)) {
                GpRequestMapping requestMapping = clazz.getAnnotation(GpRequestMapping.class);
                baseUrl = requestMapping.value();
            }
            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                if (!method.isAnnotationPresent(GpRequestParam.class)) {
                    continue;
                }
                GpRequestParam requestParam = method.getAnnotation(GpRequestParam.class);
                String regex = ("/" + baseUrl + "/" + requestParam.value().replaceAll("\\*", ".*")).replaceAll("/+", "/");
                Pattern pattern = Pattern.compile(regex);
                this.handlerMappings.add(new GpHandlerMapping(controller, method, pattern));
                log.info("Mapped" + regex + "," + method);
            }
        }
    }
}
